package wyp.lib.java.tools;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public final class WypObjectTool {

	private WypObjectTool() {
		super();
	}

	/**
	 * 可以直接使用Apache下的commons工具包中的SerializationUtils类
	 * 
	 * @param __obj
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	@SuppressWarnings("unchecked")
	public final static <T extends Serializable> T clone4Serializable(T __obj) throws IOException, ClassNotFoundException {
		T __copyObj = null;
		// 分配内存空间，写入原始对象，生成新对象
		ByteArrayOutputStream _baos = new ByteArrayOutputStream();
		ObjectOutputStream _oos = new ObjectOutputStream(_baos);
		_oos.writeObject(__obj);
		_oos.close();

		// 返回新对象，并做类型转换
		ByteArrayInputStream _bais = new ByteArrayInputStream(_baos.toByteArray());
		ObjectInputStream _ois = new ObjectInputStream(_bais);
		__copyObj = (T) _ois.readObject();
		return __copyObj;
	}
}
